package com.puff.jdbc.statement;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.w3c.dom.Node;

import com.puff.jdbc.core.Context;

/**
 * 语法
 * @author dongchao
 *
 */
public abstract class Statement {

	protected List<Statement> children = new ArrayList<Statement>();

	protected Node node;

	public Statement(Node node) {
		this.node = node;
	}

	/**
	 * 
	 * @param ctx
	 * 	Context
	 * @param localVar
	 * 	局部变量
	 */
	public abstract void execute(Context ctx, Object localVar);

	/**
	 * 添加子节点
	 * @param statement
	 * 	statement
	 */
	public void addChild(Statement statement) {
		children.add(statement);
	}

	@SuppressWarnings("rawtypes")
	protected boolean isEmpty(Object o) {
		if (o == null) {
			return true;
		} else {
			if (o instanceof String) {
				return "".equals(((String) o).trim());
			}
			if (o instanceof List) {
				return ((List) o).size() == 0;
			}
			if (o instanceof Object[]) {
				return ((Object[]) o).length == 0;
			}
		}
		return false;
	}

	protected String attr(String key) {
		Node attr = node.getAttributes().getNamedItem(key);
		if (attr == null) {
			return "";
		}
		return attr.getNodeValue();
	}

	protected boolean nullSafeEquals(Object o1, Object o2) {
		if (o1 == o2) {
			return true;
		}
		if (o1 == null || o2 == null) {
			return false;
		}
		if (o1.equals(o2)) {
			return true;
		}
		if (o1.getClass().isArray() && o2.getClass().isArray()) {
			if (o1 instanceof Object[] && o2 instanceof Object[]) {
				return Arrays.equals((Object[]) o1, (Object[]) o2);
			}
			if (o1 instanceof boolean[] && o2 instanceof boolean[]) {
				return Arrays.equals((boolean[]) o1, (boolean[]) o2);
			}
			if (o1 instanceof byte[] && o2 instanceof byte[]) {
				return Arrays.equals((byte[]) o1, (byte[]) o2);
			}
			if (o1 instanceof char[] && o2 instanceof char[]) {
				return Arrays.equals((char[]) o1, (char[]) o2);
			}
			if (o1 instanceof double[] && o2 instanceof double[]) {
				return Arrays.equals((double[]) o1, (double[]) o2);
			}
			if (o1 instanceof float[] && o2 instanceof float[]) {
				return Arrays.equals((float[]) o1, (float[]) o2);
			}
			if (o1 instanceof int[] && o2 instanceof int[]) {
				return Arrays.equals((int[]) o1, (int[]) o2);
			}
			if (o1 instanceof long[] && o2 instanceof long[]) {
				return Arrays.equals((long[]) o1, (long[]) o2);
			}
			if (o1 instanceof short[] && o2 instanceof short[]) {
				return Arrays.equals((short[]) o1, (short[]) o2);
			}
		}
		return false;
	}
}
